package com.istock.state.demo.controller;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.istock.state.demo.constants.OrderInfoStatusEnum;
import com.istock.state.demo.model.OrderInfo;
import com.istock.state.demo.service.NewOrderInfoService;

@Controller
@RequestMapping("new")
public class NewStateController {

	@Autowired
	private NewOrderInfoService orderInfoService;
	
	@RequestMapping("addOrder")
	public @ResponseBody Map<String , Object> addOrder(String name , BigDecimal amount){
		Map<String ,Object> result = new HashMap<String , Object>();
		
		if(StringUtils.isBlank(name)) {
			result.put("message", "name不能为空");
			return result;
		}
		
		if(amount == null || amount.compareTo(BigDecimal.ZERO)<=0) {
			result.put("message", "amount不能为空");
			return result;
		}
		
		OrderInfo orderInfo = orderInfoService.createOrderInfo(name, OrderInfoStatusEnum.NO_PAY.getValue(), amount);
		
		orderInfoService.executeState(orderInfo, new HashMap<String , Object>());
		
		OrderInfo newOrder = orderInfoService.findOrderInfo(orderInfo.getId());
		if(newOrder.getStatus() == OrderInfoStatusEnum.SUCCESS.getValue()) {
			result.put("message","交易成功");
		}else if(newOrder.getStatus() == OrderInfoStatusEnum.PAY_FAIL.getValue()) {
			result.put("message","支付失败");
		}else {
			result.put("message", "申请成功");
		}
		
		return result;
	}
}
